package com.bc.bcapi.service;

import cn.hutool.core.util.StrUtil;
import com.bc.bcapi.dao.*;
import com.bc.bccore.redis.RedisService;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bcmodel.consts.GlobalSettings;
import com.bc.bcmodel.consts.RedissCacheKey;
import com.bc.bcmodel.domain.*;
import com.bc.bcmodel.enums.IntegralRecordEnum;
import com.bc.bcmodel.req.*;
import com.bc.bcmodel.resp.*;
import com.bc.commoncore.util.*;
import com.bc.commonentity.common.DBContextDbType;
import com.bc.commonentity.common.DBContextHolder;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.bc.commonentity.enums.SeqNameEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rabbitmq.tools.jsonrpc.JsonRpcServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.math.BigInteger;
import java.util.concurrent.TimeUnit;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @Name T_ProjectService * @Description * @Author generation * @Date 2018/8/21 12:23:44 * @Version 1.0
 **/
@Service
public class T_ProjectService {// implements IT_ProjectService

    private static final Logger logger = LoggerFactory.getLogger(T_ProjectService.class);
    @Resource
    T_ProjectMapper t_ProjectMapper;
    @Resource
    T_SequenceService t_sequenceService;
    @Resource
    T_Project_ceokycService t_project_ceokycService;
    @Resource
    T_Project_contactService t_project_contactService;
    @Resource
    T_Project_contactMapper t_project_contactMapper;
    @Resource
    T_Project_typeService t_project_typeService;
    @Resource
    RedisService redisService;
    @Resource
    T_User_favoriteMapper t_user_favoriteMapper;
    @Resource
    T_SysconfMapper t_sysconfMapper;
    @Resource
    T_User_seller_bonusMapper t_User_seller_bonusMapper;
    @Resource
    T_Project_searchMapper t_Project_searchMapper;
    @Resource
    T_SysconfService t_sysconfService;
    @Resource
    T_Integral_recordService t_integral_recordService;
    @Resource
    T_File_upload_logMapper t_file_upload_logMapper;
    @Resource
    T_File_upload_logService t_file_upload_logService;
    @Resource
    T_Home_activityService t_home_activityService;
    @Resource
    T_Project_exchangeService t_project_exchangeService;
    @Resource
    T_Project_teamService t_project_teamService;
    @Autowired
    LanguageService languageService;
    @Autowired
    T_Project_enService t_project_enService;

    /**
     * 保存单条数据     *      * @return
     */
    public int insert(T_ProjectModel req) {
        return t_ProjectMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */
    public int insertBatch(List<T_ProjectModel> req) {
        return t_ProjectMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    public T_ProjectModel findByNamedParam(T_ProjectModel req) {
        return t_ProjectMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @return
     */
    public List<T_ProjectModel> getAllList(T_ProjectModel req) {
        return t_ProjectMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */
    public PageInfo<MngProjectListResp> getPage(MngProjectListReq req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<MngProjectListResp> list = t_ProjectMapper.getPage(req);
        for (MngProjectListResp item :
                list) {
            String statusStr = productAuthStatus(item.getStatus());
            item.setStatus_str(statusStr);
        }
        return new PageInfo<MngProjectListResp>(list);
    }

    private String productAuthStatus(int status) {
        if (status == -1) {
            return "保存草稿";
        }
        if (status == 0) {
            return "待审核";
        }
        if (status == 1) {
            return "审核通过";
        }
        if (status == 2) {
            return "审核拒绝";
        }
        return "未知";
    }

    /**
     * 更新指定对象     *      * @return
     */
    public int update(T_ProjectModel req) {
        return t_ProjectMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */
    public int delete(BigInteger id) {
        return t_ProjectMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    public long count(T_ProjectModel req) {
        return t_ProjectMapper.count(req);
    }

    /**
     * 这个方法是临时写的，只是想表达是通过类内部调用的方法，正式调用的时候使用setProject方法就可以了
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public JsonResult setProjectTmp(ProjectSetReq req) throws Exception {
        //通过CGLIB方式进行回滚，如果在同类，不同方法中，则需要使用该方法
        JsonResult js = ((T_ProjectService) AopContext.currentProxy()).setProject(req);
        if (js.getCode() == HttpReturnRnums.ParaError.value()) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        if (js.getCode() != HttpReturnRnums.Success.value()) {
            throw new Exception("error");
        }
        return js;
    }

    /**
     * 新增项目/修改项目
     */
    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public JsonResult setProject(ProjectSetReq req) {
        JsonResult js = new JsonResult();
        //默认是修改
        Boolean isAdd = false;
        /**这里的项目ID应该是查询出来的*/
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        ProjectGetByIdResp projectGetByIdResp = t_ProjectMapper.getPidByUserId(req.getUser_id());
        String pid = projectGetByIdResp == null ? "" : projectGetByIdResp.getPid();
        //非草稿
        boolean is_draft = false;
        if (StringUtils.isEmpty(pid)) {
            isAdd = true;
            pid = t_sequenceService.genSequence(SeqNameEnum.PROJECT_ID);
        }
        if (ParseHelper.ToInt(req.getIs_draft(), 0) == 1 &&
                (projectGetByIdResp == null || projectGetByIdResp.getStatus() == -1)) {
            //是草稿
            is_draft = true;
        }
        //验证，如果草稿的状态是1则无需任何验证
        if (!is_draft) {
            if (StringUtils.isEmpty(req.getIco_name()) || StringUtils.isEmpty(req.getTicker()) ||
                    req.getToken_price() == null || req.getFundraising_goal() == null ||
                    req.getTotal_tokens() == null ||
                    req.getAvailable_for_token_sale() == null || StringUtils.isEmpty(req.getAccepts()) ||
                    StringUtils.isEmpty(req.getStart_time().toString()) || StringUtils.isEmpty(req.getEnd_time().toString()) ||
                    StringUtils.isEmpty(req.getOfficicl_web()) || req.getList_contact() == null || req.getList_contact().size() <= 0 ||
                    StringUtils.isEmpty(req.getTid()) || StringUtils.isEmpty(req.getPdesc())
                    ) {
                return new JsonResult(HttpReturnRnums.ParaError);
            }
        }
        //组装
        /**组装ICO*/
        T_ProjectModel projectModel = new T_ProjectModel();
        if (is_draft) {
            //草稿
            projectModel.setStatus(-1);
        } else {
            projectModel.setStatus(0);
        }
        projectModel.setPid(pid);
        projectModel.setIco_name(req.getIco_name());
        projectModel.setTicker(req.getTicker());
        projectModel.setToken_price(req.getToken_price());
        projectModel.setFundraising_goal(req.getFundraising_goal());
        projectModel.setSold_on_pre_sale(req.getSold_on_pre_sale());
        projectModel.setTotal_tokens(req.getTotal_tokens());
        projectModel.setAvailable_for_token_sale(req.getAvailable_for_token_sale());
        projectModel.setAccepts(req.getAccepts());
        projectModel.setStart_time(req.getStart_time());
        projectModel.setEnd_time(req.getEnd_time());
        projectModel.setOfficicl_web(req.getOfficicl_web());
        projectModel.setTid(req.getTid());
        projectModel.setPdesc(req.getPdesc());
        projectModel.setBusiness_model(req.getBusiness_model());
        projectModel.setCountry(req.getCountry());
        projectModel.setInvestment_proof(t_file_upload_logService.setFilePath(req.getInvestment_proof()));
        projectModel.setMember_introduction(req.getMember_introduction());
        projectModel.setImg_roadmap(t_file_upload_logService.setFilePath(req.getImg_roadmap()));
        projectModel.setImg_project_logo(t_file_upload_logService.setFilePath(req.getImg_project_logo()));
        projectModel.setImg_white_paper(t_file_upload_logService.setFilePath(req.getImg_white_paper()));
        projectModel.setImg_scene(t_file_upload_logService.setFilePath(req.getImg_scene()));
        projectModel.setSrc_appsite(req.getSrc_appsite());
        projectModel.setUser_count(req.getUser_count());
        projectModel.setFlowing_water_count(req.getFlowing_water_count());
        projectModel.setEth_src(req.getEth_src());
        projectModel.setScene(req.getScene());
        projectModel.setUser_issave_money(req.getUser_issave_money());
        projectModel.setSave_money(req.getSave_money());
        projectModel.setExchanged_url(req.getExchanged_url());
        projectModel.setOfficial_collectmoney_url(req.getOfficial_collectmoney_url());
        projectModel.setNotallow_country(req.getNotallow_country());
        projectModel.setExchange_name(req.getExchange_name());
        projectModel.setIssetbonus(req.getIssetbonus());
        projectModel.setUser_id(req.getUser_id());
        projectModel.setVideourl(req.getVideourl());
        projectModel.setContract_eth_url(req.getContract_eth_url());
        projectModel.setToken_type(req.getToken_type());
        /**
         * 组装交所地址
         * */
//        List<T_Project_exchangeModel> listExchange = new ArrayList<T_Project_exchangeModel>();
        List<T_Project_exchangeModel> listExchangeReq = req.getListExchange();
        listExchangeReq = listExchangeReq == null ? new ArrayList<T_Project_exchangeModel>() : listExchangeReq;
        for (T_Project_exchangeModel item :
                listExchangeReq) {
            item.setPid(pid);
            item.setUser_id(req.getUser_id());
        }
        /**组装联系方式*/
        List<T_Project_contactModel> listContact = new ArrayList<T_Project_contactModel>();
        List<ProjectContactReq> listContactReq = req.getList_contact();
        listContactReq = listContactReq == null ? new ArrayList<ProjectContactReq>() : listContactReq;
        for (ProjectContactReq item :
                listContactReq) {
            T_Project_contactModel t_project_contactModel = new T_Project_contactModel();
            t_project_contactModel.setContact_name(item.getContact_name());
            t_project_contactModel.setContact_value(item.getContact_value());
            t_project_contactModel.setPid(pid);
            listContact.add(t_project_contactModel);
        }
        /**组装ceo kyc*/
        T_Project_ceokycModel t_project_ceokycModel = new T_Project_ceokycModel();
        t_project_ceokycModel.setPid(pid);
        t_project_ceokycModel.setTrue_name(req.getTrue_name());
        t_project_ceokycModel.setPassport_code(req.getPassport_code());
        t_project_ceokycModel.setAddress(req.getAddress());
        t_project_ceokycModel.setImg_address(t_file_upload_logService.setFilePath(req.getImg_address()));
        t_project_ceokycModel.setImg_passport_front(t_file_upload_logService.setFilePath(req.getImg_passport_front()));
        t_project_ceokycModel.setImg_passport_after(t_file_upload_logService.setFilePath(req.getImg_passport_after()));
        t_project_ceokycModel.setImg_passport_hold(t_file_upload_logService.setFilePath(req.getImg_passport_hold()));
        t_project_ceokycModel.setSrc_linkedin(req.getSrc_linkedin());
        t_project_ceokycModel.setSrc_resume(t_file_upload_logService.setFilePath(req.getSrc_resume()));
        /**组装项目团队*/
        List<T_Project_teamModel> listTeam = new ArrayList<T_Project_teamModel>();
        List<T_Project_teamModel> listTeamReq = req.getList_team();
        listTeamReq = listTeamReq == null ? new ArrayList<T_Project_teamModel>() : listTeamReq;
        for (T_Project_teamModel item :
                listTeamReq) {
            T_Project_teamModel t_project_teamModel = new T_Project_teamModel();
            t_project_teamModel.setHead_img(t_file_upload_logService.setFilePath(item.getHead_img()));
            t_project_teamModel.setIsdel(0);
            t_project_teamModel.setLinkedin(item.getLinkedin());
            t_project_teamModel.setUdesc(item.getUdesc());
            t_project_teamModel.setUname(item.getUname());
            t_project_teamModel.setUtitle(item.getUtitle());
            t_project_teamModel.setPid(pid);
            listTeam.add(t_project_teamModel);
        }
        if (isAdd) {
            //insert
            if (t_ProjectMapper.insert(projectModel) <= 0) {
                return new JsonResult(HttpReturnRnums.PROJECT_INSERT_ERROR);
            }
            if (t_project_ceokycService.insert(t_project_ceokycModel) <= 0) {
                return new JsonResult(HttpReturnRnums.PROJECT_INSERT_ERROR);
            }
        } else {
            //update
            projectModel.setModify_time(DateUtil.getToday());
            if (t_ProjectMapper.update(projectModel) <= 0) {
                return new JsonResult(HttpReturnRnums.PROJECT_UPDATE_ERROR);
            }
            if (t_project_ceokycService.update(t_project_ceokycModel) <= 0) {
                return new JsonResult(HttpReturnRnums.PROJECT_UPDATE_ERROR);
            }
            t_project_exchangeService.delete(pid);
            t_project_contactService.delete(pid);
            t_project_teamService.delete(pid);
        }
        if (listContact != null && listContact.size() > 0 &&
                t_project_contactService.insertBatch(listContact) <= 0) {
            return new JsonResult(HttpReturnRnums.PROJECT_INSERT_ERROR);
        }
        if (listExchangeReq != null && listExchangeReq.size() > 0 &&
                t_project_exchangeService.insertBatch(listExchangeReq) <= 0) {
            return new JsonResult(HttpReturnRnums.PROJECT_INSERT_ERROR);
        }
        if (listTeamReq != null && listTeamReq.size() > 0 &&
                t_project_teamService.insertBatch(listTeam) <= 0) {
            return new JsonResult(HttpReturnRnums.PROJECT_INSERT_ERROR);
        }
        return js;
    }

    /**
     * 通过pid获取项目详情
     */
    public JsonResult getbypid(ProjectGetByIdReq req) {
        JsonResult js = new JsonResult();
        ProjectGetByIdResp result = t_ProjectMapper.getByPid(req);
        if (result == null) {
            return new JsonResult(HttpReturnRnums.PROJECT_NOT_EXISTS);
        }
        req.setPid(result.getPid());
        List<ProjectContactReq> list_contact = t_project_contactMapper.getByPid(req.getPid());
        result.setList_contact(list_contact);
        /**
         * 拼接附件路径
         * */
        //joinProjectImgStr(result);
        /**
         * 查询白皮书-开始
         * */
        if (!StringUtils.isEmpty(result.getImg_white_paper())) {
            T_File_upload_logModel uploadLogWhite = new T_File_upload_logModel();
            uploadLogWhite.setFile_src(result.getImg_white_paper());
            T_File_upload_logModel whitePaperModel = t_file_upload_logMapper.findByNamedParam(uploadLogWhite);
            if (whitePaperModel != null) {
                whitePaperModel.setFile_src(WebConfig.getImgUrl() + whitePaperModel.getFile_src());
            }
            result.setWhite_paperModel(whitePaperModel);
        }
        /**
         * 查询白皮书-结束
         * 查询简历附件-开始
         * */
        if (!StringUtils.isEmpty(result.getSrc_resume())) {
            T_File_upload_logModel uploadLogResume = new T_File_upload_logModel();
            uploadLogResume.setFile_src(result.getSrc_resume());
            T_File_upload_logModel resumeModel = t_file_upload_logMapper.findByNamedParam(uploadLogResume);
            if (resumeModel != null) {
                resumeModel.setFile_src(WebConfig.getImgUrl() + resumeModel.getFile_src());
            }
            result.setResumeModel(resumeModel);
        }
        /**
         * 查询简历附件-结束
         * */
        result.setImg_domain(WebConfig.getImgUrl());
        js.setData(result);
        return js;
    }

    private void joinProjectImgStr(ProjectGetByIdResp projectModel) {
        projectModel.setInvestment_proof(t_file_upload_logService.getFilePath(projectModel.getInvestment_proof()));
        projectModel.setImg_roadmap(t_file_upload_logService.getFilePath(projectModel.getImg_roadmap()));
        projectModel.setImg_project_logo(t_file_upload_logService.getFilePath(projectModel.getImg_project_logo()));
        projectModel.setImg_white_paper(t_file_upload_logService.getFilePath(projectModel.getImg_white_paper()));
        projectModel.setImg_scene(t_file_upload_logService.getFilePath(projectModel.getImg_scene()));
    }

    /**
     * ICO审核信息查询；通过pid获取项目状态
     */
    public JsonResult getStatusByPid(@RequestBody ProjectGetByIdReq req) {
        JsonResult js = new JsonResult();
        ProjectStatusResp result = t_ProjectMapper.getStatusByPid(req);
        if (result == null) {
            return new JsonResult(HttpReturnRnums.PROJECT_NOT_EXISTS);
        }
        js.setData(result);
        return js;
    }

    /**
     * 获取前台搜索条件
     */
    public JsonResult getSearchParam(HttpServletRequest request) {
        JsonResult js = new JsonResult();
        ProjectSearchParamResp resp = new ProjectSearchParamResp();
        String language = CookieUtils.getCookie(request, "local");
        if (StringUtils.isEmpty(language)) {
            language = "zh";
        }
        boolean is_english = language.equals("en") ? true : false;

        /*组装状态开始*/
        List<ProjectSearchStatusParamResp> listStatus =
                new ArrayList<ProjectSearchStatusParamResp>();
        ProjectSearchStatusParamResp is_transaction = new ProjectSearchStatusParamResp();
        is_transaction.setKey("is_transaction");
        is_transaction.setValue("实时交易");
        if (is_english) {
            is_transaction.setValue("Trading");
        }
        is_transaction.setIs_important(1);
        listStatus.add(is_transaction);

        ProjectSearchStatusParamResp is_bonus = new ProjectSearchStatusParamResp();
        is_bonus.setKey("is_bonus");
        is_bonus.setValue("有bonus");
        if (is_english) {
            is_bonus.setValue("Bonus");
        }
        is_bonus.setIs_important(1);
        listStatus.add(is_bonus);

        ProjectSearchStatusParamResp expert_comment_count = new ProjectSearchStatusParamResp();
        expert_comment_count.setKey("expert_comment_count");
        expert_comment_count.setValue("专家点评");
        if (is_english) {
            expert_comment_count.setValue("Expert Analysis");
        }
        expert_comment_count.setIs_important(1);
        listStatus.add(expert_comment_count);

        ProjectSearchStatusParamResp is_sto = new ProjectSearchStatusParamResp();
        is_sto.setKey("is_eos");
        is_sto.setValue("EOS");
        if (is_english) {
            is_sto.setValue("EOS");
        }
        is_sto.setIs_important(1);
        listStatus.add(is_sto);

        ProjectSearchStatusParamResp is_video = new ProjectSearchStatusParamResp();
        is_video.setKey("is_video");
        is_video.setValue("有视频分析");
        if (is_english) {
            is_video.setValue("Video");
        }
        listStatus.add(is_video);

        ProjectSearchStatusParamResp is_user = new ProjectSearchStatusParamResp();
        is_user.setKey("is_user");
        is_user.setValue("有用户量");
        if (is_english) {
            is_user.setValue("User");
        }
        listStatus.add(is_user);

        ProjectSearchStatusParamResp is_flowing_water = new ProjectSearchStatusParamResp();
        is_flowing_water.setKey("is_flowing_water");
        is_flowing_water.setValue("有流水");
        if (is_english) {
            is_flowing_water.setValue("Sales Revenue");
        }
        listStatus.add(is_flowing_water);

        ProjectSearchStatusParamResp is_real_industry = new ProjectSearchStatusParamResp();
        is_real_industry.setKey("is_real_industry");
        is_real_industry.setValue("有实体产业");
        if (is_english) {
            is_real_industry.setValue("Industry Entity");
        }
        listStatus.add(is_real_industry);

        ProjectSearchStatusParamResp is_code_public = new ProjectSearchStatusParamResp();
        is_code_public.setKey("is_code_public");
        is_code_public.setValue("代码公开");
        if (is_english) {
            is_code_public.setValue("Exposed Code");
        }
        listStatus.add(is_code_public);



        /*组装状态结束*/
        resp.setListStatus(listStatus);
        resp.setListType(t_project_typeService.getType(request));
        js.setData(resp);
        return js;
    }

    /**
     * 字符串拼装
     */
    private List<String> getSplitStr(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        String[] tids = str.split(",");
        List<String> list = new ArrayList<String>();
        for (String item :
                tids) {
            if (item.equals("")) {
                continue;
            }
            list.add(item);
        }
        return list;
    }

    /**
     * 获取搜索列表页数据
     */
    public JsonResult search(ProjectSearchParamReq req,
                             HttpServletRequest request, HttpServletResponse response) {
        JsonResult js = new JsonResult();
        String language =
                languageService.getCurrentLanguage(request, response, GlobalSettings.LANGUAGE);
        ProjectSearchResp resp = t_ProjectMapper.searchCount(req);
        if (resp == null) {
            resp = new ProjectSearchResp();
        }
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        //类型拼装
//        req.settid(getSplitStr(req.getTid()));
        //国家拼装
//        req.setListCountry(getSplitStr(req.getCountry()));
        List<ProjectSearchInfoResp> list = t_ProjectMapper.search(req);
//        List<ProjectSearchInfoResp> list = listPageInfo.getList();
        for (ProjectSearchInfoResp item :
                list) {
            item.setImg_project_logo(t_file_upload_logService.getFilePath(item.getImg_project_logo()));
            //切换简述的中英文,如果是英文，且英文不为空
            if (language.equals("en") && !StrUtil.isEmpty(item.getPdesc_en())) {
                item.setPdesc(item.getPdesc_en());
            }
        }
        initProject(req.getUser_id(), list);
        PageInfo<ProjectSearchInfoResp> pageInfo =
                new PageInfo<ProjectSearchInfoResp>(list);
        //如果是第一页 ，需要把活动的项目放到前面
        if (req.getPage_index() == 1) {
            //把广告值入到项目列表
//            list = list == null ? new ArrayList<ProjectSearchInfoResp>() : list;
            List<ProjectSearchInfoResp> listActivity = new ArrayList<ProjectSearchInfoResp>();
            List<T_Home_activityModel> listHomeActivity = t_home_activityService.getHomeActivity(request, response);
            for (T_Home_activityModel item :
                    listHomeActivity) {
                ProjectSearchInfoResp resp1 = new ProjectSearchInfoResp();
                resp1.setIs_ad(1);
                //图片地址
                resp1.setIco_name(item.getBanner_name());
                //链接
                resp1.setPdesc(item.getBanner_url());
                listActivity.add(resp1);
            }
            for (ProjectSearchInfoResp item :
                    list) {
                listActivity.add(item);
            }
            list = listActivity;

        }
        if (req.getPage_index() == 1) {
            PageInfoExt<ProjectSearchInfoResp> pageExt = new PageInfoExt<ProjectSearchInfoResp>
                    (list, pageInfo.getTotal(), req.getPage_index(),
                            req.getPage_size());
            resp.setInfo(pageExt);
        } else {
            resp.setInfo(pageInfo);
        }
        js.setData(resp);
        return js;
    }

    /**
     * 组装response里的我的购物车，我的收藏，我的提醒
     */
    private void initProject(String user_id, List<ProjectSearchInfoResp> list) {
        /**查询用户的我喜欢，我的收藏，我的提醒-开始*/
        if (StringUtils.isEmpty(user_id)) {
            return;
        }
        ProjectFavoriteReq projectFavoriteReq = new ProjectFavoriteReq();
        List<String> listFavoritePid = new ArrayList<String>();
        for (ProjectSearchInfoResp item : list) {
            listFavoritePid.add(item.getPid());
        }
        projectFavoriteReq.setListPid(listFavoritePid);
        projectFavoriteReq.setUser_id(user_id);
        if (null != listFavoritePid && listFavoritePid.size() > 0) {
            List<T_User_favoriteModel> projectSearchInfoRespList =
                    t_ProjectMapper.getFavoritTag(projectFavoriteReq);
            for (ProjectSearchInfoResp item :
                    list) {
                for (T_User_favoriteModel item_like :
                        projectSearchInfoRespList) {
                    if (item.getPid().equals(item_like.getPid())) {
                        int typeid = item_like.getType_id().intValue();
                        if (typeid == 1) {
//            is_cart 用户是否标注购物车;
                            item.setIs_cart(1);
                        }
                        if (typeid == 2) {
//            is_user_favorite 用户是否标注我喜欢;
                            item.setIs_user_favorite(1);
                        }
                        if (typeid == 3) {
//            is_user_remind 用户是否标注提醒;
                            item.setIs_user_remind(1);
                        }
                    }
                }
            }
        }
//        T_Project_tag_relationModel t_project_tag_relationModel = new T_Project_tag_relationModel();
//        t_project_tag_relationModel.setUser_id(user_id);
//        t_project_tag_relationModel.setPid(req.getPid());
//        List<T_Project_tag_relationModel> listRelationModel =
//                t_project_tag_relationMapper.findByNamedParamList(t_project_tag_relationModel);

        //这里需要判断一下，如果user_id有值需要把这里的每一个ico进行打标
        // 比如，是否为我喜欢，我的收藏，我加入的购物车
        /**查询用户的我喜欢，我的收藏，我的提醒-结束*/
    }

    /**
     * 写入查看次数
     */
//    private void setViewCount(String pid,
//                              HttpServletRequest request,
//                              HttpServletResponse response) {
//        String ip = IPUtil.getIpAddr(request);
//        logger.info("您的真实IP是" + ip);
//        String timekey = RedissCacheKey.Project_viewCount_Time_Key + "_" + pid + "_" + ip;
//        String timevalue = redisService.get(timekey);
//        getViewCount(pid);
//        if (timevalue != null && !timevalue.isEmpty()) {
//            //说明五分钟内已经访问过了。
//            return;
//        }
//        redisService.set(timekey, "1", 5, TimeUnit.MINUTES);
//    }
//
//    private int getViewCount(String pid) {
//        String viewcountkey = RedissCacheKey.Project_ViewCount_Key + pid;
//        String viewCountValue = redisService.get(viewcountkey);
//        Integer viewCountInt = ParseHelper.ToInt(viewCountValue, 1000);
//        redisService.set(viewcountkey, viewCountInt.toString());
//    }

    /**
     * 设置详情页的我的购物车，收藏，提醒
     */
    private void setLike(ProjectDetailReq req, ProjectDetailResp resp) {
        if (StringUtils.isEmpty(req.getUser_id())) {
            return;
        }
        T_User_favoriteModel t_user_favoriteModel = new T_User_favoriteModel();
        t_user_favoriteModel.setUser_id(req.getUser_id());//买家用户ID
        t_user_favoriteModel.setPid(req.getPid());
        t_user_favoriteModel.setIsdel(0);
        List<T_User_favoriteModel> resultFavorite = t_user_favoriteMapper.findByNamedParamList(t_user_favoriteModel);
        if (resultFavorite == null || resultFavorite.size() <= 0) {
            return;
        }
        for (T_User_favoriteModel item_like :
                resultFavorite) {
            int typeid = item_like.getType_id().intValue();
            if (typeid == 1) {
//            is_cart 用户是否标注购物车;
                resp.setIs_cart(1);
            }
            if (typeid == 2) {
//            is_user_favorite 用户是否标注我喜欢;
                resp.setIs_user_favorite(1);
            }
            if (typeid == 3) {
//            is_user_remind 用户是否标注提醒;
                resp.setIs_user_remind(1);
            }
        }
    }

    /**
     * 设置用户bonus
     */
    private void setBonus(ProjectDetailResp resp) {
        if (resp.getIssetbonus() != 1) {
            return;
        }
        String seller_user_id = resp.getUser_id();
        T_User_seller_bonusModel req = new T_User_seller_bonusModel();
        req.setUser_id(seller_user_id);
        List<T_User_seller_bonusModel> list =
                t_User_seller_bonusMapper.findByNamedParamList(req);
        if (list == null || list.size() <= 0) {
            return;
        }
        resp.setT_user_seller_bonusModelList(list);
    }

    /**
     * 是否显示购物车逻辑，是否向管理后台账户充值了
     */
    public int SetIs_transaction(String pid) {
        int is_transaction = 0;
        BigDecimal projectBalance = t_Project_searchMapper.getProjectBalanceByPid(pid);
        projectBalance = projectBalance == null ? new BigDecimal(0) : projectBalance;
        int projectBalancePare = projectBalance.compareTo(BigDecimal.ZERO);
        if (projectBalancePare > 0) {
            is_transaction = 1;
        }
        return is_transaction;
    }

    private void getProjectEn(HttpServletRequest request,
                              HttpServletResponse response,
                              ProjectDetailResp resp) {

        /**
         * 查询白皮书
         * */
        T_File_upload_logModel t_file_upload_logModel = new T_File_upload_logModel();
        if (!StrUtil.isEmpty(resp.getImg_white_paper())) {

            t_file_upload_logModel.setFile_src(resp.getImg_white_paper());
            T_File_upload_logModel whitePaperModel = t_file_upload_logMapper.findByNamedParam(t_file_upload_logModel);
            if (whitePaperModel != null) {
                whitePaperModel.setFile_src(WebConfig.getImgUrl() + whitePaperModel.getFile_src());
            }
            resp.setWhite_paperModel(whitePaperModel);
        }

        String language = languageService.getCurrentLanguage(request, response, GlobalSettings.LANGUAGE);
        if (language.equals("en")) {
            //查询英文相关数据
            T_Project_enModel t_project_enModel = new T_Project_enModel();
            t_project_enModel.setPid(resp.getPid());
            T_Project_enModel t_project_enModelReuslt = t_project_enService.findByNamedParam(t_project_enModel);
            if (t_project_enModelReuslt == null || StrUtil.isEmpty(t_project_enModelReuslt.getPdesc())) {
                return;
            }
            resp.setPdesc(t_project_enModelReuslt.getPdesc());
        }

    }

    /**
     * 项目详情页方法
     */
    public JsonResult detail(ProjectDetailReq req,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        JsonResult js = new JsonResult();
//        String language =
//                languageService.getCurrentLanguage(request, response, GlobalSettings.LANGUAGE);
        String pid = req.getPid();
        if (pid.equals("")) {
            return new JsonResult(HttpReturnRnums.PROJECT_NOT_EXISTS);
        }
        ProjectDetailResp resp = t_ProjectMapper.getDetailByPid(pid);
        if (resp == null) {
            return new JsonResult(HttpReturnRnums.PROJECT_NOT_EXISTS);
        }
        getProjectEn(request, response, resp);
//        setViewCount(pid, request, response);
        /**
         * 设置同列表页一至的查看次数等快照信息
         * */
        T_Project_searchModel t_project_searchModel = new T_Project_searchModel();
        t_project_searchModel.setPid(req.getPid());
        T_Project_searchModel resultSearchModel =
                t_Project_searchMapper.findByNamedParam(t_project_searchModel);
        if (resultSearchModel != null) {
            resp.setView_count(resultSearchModel.getView_count());
            resp.setFavorite_count(resultSearchModel.getFavorite_count());
            resp.setLike_count(resultSearchModel.getLike_count());
            resp.setProfessional_analysis_count(resultSearchModel.getProfessional_analysis_count());
            resp.setFinish_rate(resultSearchModel.getFinish_rate());
            resp.setTotal_amount(resultSearchModel.getTotal_amount());
            resp.setExists_amount(resultSearchModel.getExists_amount());
            resp.setIs_transaction(resultSearchModel.getIs_transaction());
        }
        BigDecimal platform_commission = t_sysconfService.getPlatformCommission();
        //平台佣金
        resp.setPlatform_commission(platform_commission);
        //设置我喜欢，收藏，提醒
        setLike(req, resp);
        //返回bonus
        setBonus(resp);
        //绑定社交信息
        T_Project_contactModel t_project_contactModel = new T_Project_contactModel();
        t_project_contactModel.setPid(req.getPid());
        List<T_Project_contactModel> listContact =
                t_project_contactMapper.findByNamedParamList(t_project_contactModel);
        if (listContact != null && listContact.size() > 0) {
            resp.setListContact(listContact);
        }

        /**
         * 交所列表
         * */
        T_Project_exchangeModel t_project_exchangeModel = new T_Project_exchangeModel();
        t_project_exchangeModel.setPid(pid);
        List<T_Project_exchangeModel> listExchangResult =
                t_project_exchangeService.getAllList(t_project_exchangeModel);
        resp.setListExchange(listExchangResult);
        /**
         * 交所列表
         * */
        resp.setImg_domain(WebConfig.getImgUrl());
        /**项目团队*/
        T_Project_teamModel t_project_teamModel = new T_Project_teamModel();
        t_project_teamModel.setPid(pid);
        List<T_Project_teamModel> listTeam = t_project_teamService.getAllList(t_project_teamModel);
        resp.setList_team(listTeam);

        js.setData(resp);
        if (!StringUtils.isEmpty(req.getUser_id())) {
            //浏览ICO+积分
            t_integral_recordService.threadInsertIntegralRecord(IntegralRecordEnum.LLICO, pid, req.getUser_id());
        }
        return js;
    }

    /**
     * 获取我的ICO
     */
    public JsonResult getMyIco(MyIcoReq req) {
        JsonResult js = new JsonResult();
        ProjectSearchResp resp = new ProjectSearchResp();
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<ProjectSearchInfoResp> list = t_ProjectMapper.getMyIco(req);
        initProject(req.getUser_id(), list);
        PageInfo<ProjectSearchInfoResp> pageInfo =
                new PageInfo<ProjectSearchInfoResp>(list);
        resp.setInfo(pageInfo);
        js.setData(resp);
        return js;
    }

    /**
     * 获取我的参与
     */
    public JsonResult getMyJoin(ProjectMyJoinReq req) {
        JsonResult js = new JsonResult();
        ProjectSearchResp resp = new ProjectSearchResp();
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<ProjectSearchInfoResp> list = t_ProjectMapper.getMyJoin(req);
        initProject(req.getUser_id(), list);
        PageInfo<ProjectSearchInfoResp> pageInfo =
                new PageInfo<ProjectSearchInfoResp>(list);
        resp.setInfo(pageInfo);
        js.setData(resp);
        return js;
    }

    /**
     * 设置(我的收藏+加入购物车+我的提醒)，typeid:{1 加入购物车 2 我收藏的ico 3 我的提醒}
     */
    public JsonResult setMyIco(ProjectSetIcoReq req) {
        int count = t_user_favoriteMapper.deleteByBuyerId(req);
        if (count <= 0) {
            //insert,说明是删除
            T_User_favoriteModel t_user_favoriteModel = new T_User_favoriteModel();
            t_user_favoriteModel.setPid(req.getPid());
            t_user_favoriteModel.setUser_id(req.getUser_id());
            t_user_favoriteModel.setType_id(req.getType_id());
            t_user_favoriteMapper.insert(t_user_favoriteModel);
//            增加积分
            addMyIcoIntegral(req.getType_id(), req.getPid(), req.getUser_id());
        }
        return new JsonResult(HttpReturnRnums.Success);
    }

    /**
     * 我喜欢，我的收藏，我的提醒增加积分
     */
    private void addMyIcoIntegral(int type_id, String pid, String user_id) {
        if (type_id == 1) {
            //我喜欢积分
            t_integral_recordService.threadInsertIntegralRecord(
                    IntegralRecordEnum.JRXH, pid, user_id);
        } else if (type_id == 2) {
            //收藏ICO积分
            t_integral_recordService.threadInsertIntegralRecord(
                    IntegralRecordEnum.SCICO, pid, user_id);
        }
        //提醒积分
        else if (type_id == 3) {
            t_integral_recordService.threadInsertIntegralRecord(
                    IntegralRecordEnum.SXICOTX, pid, user_id);
        }
    }

    /**
     * 审核项目
     */
    public int setAuth(MngProductAuthReq req) {
        return t_ProjectMapper.setAuth(req);
    }

    public JsonResult setContractByPid(String user_id) {
        t_ProjectMapper.setContractByPid(user_id);
        return new JsonResult();
    }

    public int getIsContract(String user_id) {
        Integer isContract = t_ProjectMapper.getIsContract(user_id);
        if (isContract == null) {
            return 0;
        }
        return isContract;
    }

    public JsonResult getProjectType() {
        JsonResult jsonResult = new JsonResult();
        String projectType = WebConfig.getProjectType();
        if (StrUtil.isEmpty(projectType)) {
            return jsonResult;
        }
        String[] arrProjectType = projectType.split(",");
        List<String> list = new ArrayList<String>();
        for (String item :
                arrProjectType) {
            if (StrUtil.isEmpty(item)) {
                continue;
            }
            list.add(item);
        }
        jsonResult.setData(list);
        return jsonResult;
    }
}